﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Xml;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.VersionControl.Common;

using Sogeti.VSExtention;

namespace Sogeti.SourceControlWrapper
{

	public class WI
	{
		public string Title;
		public string Description;
		public string Type;
		public string AreaPath;
		public string IterationPath;
		public Dictionary<string, object>   customFields;


		public WI()
		{
			customFields = new Dictionary<string, object>();
		}

	}

	public class SCWrapper
	{

		protected TfsTeamProjectCollection tpCollection;
		protected string teamProjectName;
		protected VersionControlServer         scSrv;

		public SCWrapper(string tpCollectionUrl, string aTeamProjectName)
		{

			tpCollection = new TfsTeamProjectCollection(new Uri(tpCollectionUrl));
			teamProjectName = aTeamProjectName;

			scSrv = (VersionControlServer)tpCollection.GetService(typeof(VersionControlServer));
		}

		public SCWrapper(TeamExplorerIntergator teamExplorer)
		{

			tpCollection = teamExplorer.tpCollection;
			teamProjectName = teamExplorer.tpName;

			scSrv = (VersionControlServer)tpCollection.GetService(typeof(VersionControlServer));
		}

		public string RootFolder()
		{
			return scSrv.GetTeamProject(teamProjectName).ServerItem;
		}




		public  bool FileExist(string fileName)
		{
			return scSrv.ServerItemExists(fileName, ItemType.File);
		}

		
		public Stream Get(string filename)
		{
			Item itm = scSrv.GetItem(filename);
			return  itm.DownloadFile();
			
		}

		public void  Save(string filename,  XmlDocument xml)
		{
			// Using temporary directory for the workspace mapping
			var dir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()));

			string serverPath= filename.Substring(0, filename.LastIndexOf(@"/"));
			string fileNamePart= filename.Replace(serverPath + @"/", "");

			if (!dir.Exists)
			{
				dir.Create();
			}
	 
			try
			{	   
				// Query for workspaces and delete if found.	    
				
				string username=GetUserName();

				var ws = scSrv.QueryWorkspaces("temp", username, Environment.MachineName).FirstOrDefault();
				if (ws != null)
				{
					ws.Delete();
				}
	 
				// Create the workspace with a mapping to the temporary folder.
				ws = scSrv.CreateWorkspace("temp", username, string.Empty, new WorkingFolder[] { new WorkingFolder(  serverPath, dir.FullName) });
				ws.Get(new GetRequest(filename, RecursionType.None, VersionSpec.Latest) ,GetOptions.None );
//                ws.Get();

				// Create a file and add it as a pending change.
				var file = Path.Combine(dir.FullName, fileNamePart);
				FileInfo fi = new FileInfo(file);
				if (fi.Exists)
				{
					fi.Attributes = FileAttributes.Normal;
					xml.Save(file);
					ws.PendEdit(file);
				}
				else
				{
					xml.Save(file);
					ws.PendAdd(file);
				}
	 
				// Finally check-in, don't trigger a Continuous Integration build and override gated check-in.
				var wip = new WorkspaceCheckInParameters(ws.GetPendingChanges(), "***NO_CI***")
				{
					// Enable the override of gated check-in when the server supports gated check-ins.
					OverrideGatedCheckIn = ((CheckInOptions2)scSrv.SupportedFeatures & CheckInOptions2.OverrideGatedCheckIn) == CheckInOptions2.OverrideGatedCheckIn,
					PolicyOverride = new PolicyOverrideInfo("Check-in from IterationnManaager.", null)
				};
				ws.CheckIn(wip);
				
			}
			finally
			{
				if (dir.Exists)
				{
					dir.Attributes = FileAttributes.Normal;
					dir.Delete(true);
				}
			}
	  
		}


        private string GetUserName()
        {
            string username = null;

            try
            {


                if (tpCollection.Credentials != null)
                {

                    if (tpCollection.Credentials is System.Net.NetworkCredential)
                    {
                        username = ((System.Net.NetworkCredential)tpCollection.Credentials).Domain + @"\" + ((System.Net.NetworkCredential)tpCollection.Credentials).UserName;

                    }
                }
            }
            catch (Exception ex)
            {
            }
            try
            {
                if (username == null || username == "\\")
                {
                    if (tpCollection.AuthorizedIdentity != null)
                    {

                        if (tpCollection.AuthorizedIdentity.UniqueName != "")
                        {
                            username = tpCollection.AuthorizedIdentity.UniqueName;
                        }
                    }
                }
            }
            catch (Exception ex)
            { }

            try
            {
                if (username == null)
                {
                    username = Environment.UserName;
                }
            }
            catch (Exception ex)
            { }

            return username;
        }
 
	}
		
}
